package com.example.stars_project_android.index;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stars_project_android.R;
import com.example.stars_project_android.personalCenter.User;
import com.example.stars_project_android.util.Constant;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.constants.EaseConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 创建房间界面
 */
public class CreateRoom extends AppCompatActivity implements View.OnClickListener {
    private Button btnDecrease, btnAdd, btnCreate;  //返回按钮，人数减一按钮，人数加一按钮，创建时空按钮
    private ImageButton btnCreateReturn;
    private EditText edSpaceName, etSpaceDetail, edNum;  //时空名，时空描述
    private Spinner spinner;  //时空类型
    private String spaceAttribute;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    private boolean one_selected = false;

    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                Toast.makeText(CreateRoom.this,jsonObject.getString("date"),Toast.LENGTH_SHORT).show();
                if (code == 200) {
                        Intent intent = new Intent(getApplicationContext(),
                                RoomDetail.class);
                    intent.putExtra(EaseConstant.EXTRA_CONVERSATION_ID,msgCon);
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.GroupChat);
                        startActivity(intent);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_room);
        
        //绑定控件对象
        setView();
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.black));
                String[] languages = getResources().getStringArray(R.array.spinner);
                spaceAttribute = languages[pos];
                Log.e("时空类型",spaceAttribute);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback

            }
        });

    }

    /**
     * 获取控件对象
     */
    private void setView() {
        spinner = findViewById(R.id.sp_attribute);
        btnCreateReturn = findViewById(R.id.btn_create_return);
        btnCreateReturn.setOnClickListener(this);
        btnDecrease = findViewById(R.id.btn_decrease);
        btnDecrease.setOnClickListener(this);
        btnAdd = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(this);
        btnCreate = findViewById(R.id.btn_create);
        btnCreate.setOnClickListener(this);
        edSpaceName = findViewById(R.id.et_space_name);
        etSpaceDetail = findViewById(R.id.et_space_detail);
        edNum = findViewById(R.id.et_number);
    }

    /**
     * 获取网络连接
     */
    private void getConn() {
        //向后端传递页面上获取的手机号和密码。
        JSONObject jsonObject = new JSONObject();
        try {
            //时空名称
            jsonObject.put("roomName",edSpaceName.getText().toString());
            //时空容纳人数
            jsonObject.put("userCountMax",edNum.getText().toString());
            //创建时空的用户用户名
            jsonObject.put("userPhone", Constant.phone);
            //时空描述
            jsonObject.put("roomDescribe",etSpaceDetail.getText().toString());
            //时空类型
            jsonObject.put("roomAttribute",spaceAttribute);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Log.e("json格式",jsonObject.toString());
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.7:8080/room/createRoom")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("okhttp","请求成功");
                //处理后端的数据
                response = okHttpClient.newCall(request).execute();
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_create_return:
                //点击返回到点击之前的状态
                //调用生命周期函数？
                //直接返回首页
                Intent intent = new Intent(this,Index.class);
                startActivity(intent);
                break;
            case R.id.btn_add:
                //点击将人数加一
                edNum.setText((Integer.valueOf(edNum.getText().toString()) + 1) + "");
                break;
            case R.id.btn_decrease:
                //点击将人数减一
                //做判断的目的是不让值小于0
                if (edNum.getText().toString().equals("0")) {
                    edNum.setText(0 + "");
                }else {
                    edNum.setText((Integer.valueOf(edNum.getText().toString()) - 1) + "");
                }
                break;
            case R.id.btn_create:
                //点击创建房间
                getConn();
                //创建成功后跳转到房间详情页面
                break;
        }
    }
}